package com.dog.modules.system.web;

import com.dog.framework.core.model.ResponseResult;
import com.dog.framework.log.annotation.OperateLog;
import com.dog.framework.log.enums.BusinessType;
import com.dog.modules.system.convert.SysOrgConvert;
import com.dog.modules.system.domain.SysOrg;
import com.dog.modules.system.api.vo.SysOrgVO;
import com.dog.modules.system.service.SysOrgService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.List;

/**
 * 机构管理
 *
 * @author 阿沐 babamu@126.com
 * <a href="https://maku.net">MAKU</a>
 */
@RestController
@RequestMapping("/sys/org")
@Tag(name = "机构管理")
@AllArgsConstructor
public class SysOrgController {
    private final SysOrgService sysOrgService;

    @GetMapping("/list")
    @Operation(summary = "列表")
    public ResponseResult<List<SysOrgVO>> list() {
        List<SysOrgVO> list = sysOrgService.getList();
        return ResponseResult.success(list);
    }

    @GetMapping("{id}")
    @Operation(summary = "信息")
    public ResponseResult<SysOrgVO> get(@PathVariable("id") Long id) {
        SysOrg entity = sysOrgService.getById(id);
        SysOrgVO vo = SysOrgConvert.INSTANCE.convert(entity);
        // 获取上级机构名称
        if (entity.getPid() != null) {
            SysOrg parentEntity = sysOrgService.getById(entity.getPid());
            vo.setParentName(parentEntity.getName());
        }
        return ResponseResult.success(vo);
    }

    @PostMapping
    @Operation(summary = "保存")
    @OperateLog(businessType = BusinessType.INSERT)
    public ResponseResult<String> save(@RequestBody @Valid SysOrgVO vo) {
        sysOrgService.save(vo);
        return ResponseResult.success();
    }

    @PutMapping
    @Operation(summary = "修改")
    @OperateLog(businessType = BusinessType.UPDATE)
    public ResponseResult<String> update(@RequestBody @Valid SysOrgVO vo) {
        sysOrgService.update(vo);
        return ResponseResult.success();
    }

    @DeleteMapping("{id}")
    @Operation(summary = "删除")
    @OperateLog(businessType = BusinessType.DELETE)
    public ResponseResult<String> delete(@PathVariable("id") Long id) {
        sysOrgService.delete(id);
        return ResponseResult.success();
    }

}